package com.haoxuer.discover.pays.controller.front;

import com.haoxuer.discover.pay.weixin.domain.PayBack;
import com.haoxuer.discover.pays.data.service.PaymentService;
import com.haoxuer.discover.pays.utils.StreamUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.DomDriver;
import jodd.util.StringUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;


@Scope("prototype")
@Controller
public class PaySiteController implements InitializingBean,DisposableBean {
  
  
  

  @Override
  public void afterPropertiesSet() throws Exception {
    System.out.println("init site");
  }
  
  @Override
  public void destroy() throws Exception {
    System.out.println("destroy site");
  }
  
  @Autowired
  private PaymentService paymentService;
  
  @RequestMapping(value = "/weixinnotifyurl")
  public String weixinnotifyurl(HttpServletRequest request, ModelMap model) {
    try {
      ServletInputStream stream = request.getInputStream();
      byte[] datas = StreamUtil.readBytes(stream);
      String msg = new String(datas);
      System.out.println(msg);
      
      
      XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder()));
      xstream.alias("xml", PayBack.class);
      msg = StringUtil.convertCharset(msg, Charset.forName("ISO-8859-1"), Charset.forName("UTF-8"));
      PayBack result = (PayBack) xstream.fromXML(msg);
      
      if ("SUCCESS".equals(result.getResult_code()) && "SUCCESS".equals(result.getReturn_code())) {
        String out_trade_no = result.getOut_trade_no();
        paymentService.handle(result);
        
        model.addAttribute("return_code", "SUCCESS");
        model.addAttribute("return_msg", "OK");
      } else {
        model.addAttribute("return_code", "FAIL");
        model.addAttribute("return_msg", "OK");
      }
    } catch (Exception e) {
      e.printStackTrace();
      model.addAttribute("return_code", "FAIL");
      model.addAttribute("return_msg", "OK");
    }
    return "common/payback";
  }
}
